import { RadioGroup } from '@designable/formily-antd/esm/locales/Radio';
import {
  Button,
  Form,
  FormInstance,
  Input,
  Radio,
  Select,
  Space,
  Switch,
} from 'antd';
import { DefaultOptionType } from 'antd/lib/select';
import React, { useEffect, useRef, useState } from 'react';
import { Link } from 'umi';

export type IColumnFormItemProps = {
  onFinish: (formData: any) => void;
  initFormData: any;
};

export default function ColumnFormItem(props: IColumnFormItemProps) {
  const [isDisable, setIsDisable] = useState(false);
  const myFormRef = useRef<FormInstance>();
  const typeOptions: DefaultOptionType[] = [
    {
      label: '文本',
      value: 'text',
      key: 'text',
    },
    {
      label: '节点',
      value: 'node',
      key: 'node',
    },
    {
      label: '自定义方法',
      value: 'customFunction',
      key: 'customFunction',
    },
  ];

  const requiredRule = [
    {
      required: true,
      message: '此项必填',
    },
  ];

  const handleFinish = (formData: any) => {
    console.log('表单提交结束 ---> ', formData);
    setIsDisable(true);
    props.onFinish &&
      props.onFinish({
        ...formData,
        __disabled: true,
      });
  };

  useEffect(() => {
    if (!myFormRef.current) return;
    const { initFormData = {}} = props;
    console.log('props.initFormData --> ', props.initFormData);
    myFormRef.current.setFieldsValue({
      dataIndex: initFormData.dataIndex,
      title: initFormData.title,
      fix: initFormData.fix,
      type: initFormData.type,
    });
  }, [props.initFormData]);

  return (
    <Form
      labelCol={{ span: 4 }}
      ref={myFormRef}
      disabled={isDisable}
      onFinish={handleFinish}
    >
      <Form.Item label="列名" name="title" rules={requiredRule}>
        <Input placeholder="请输入列名" />
      </Form.Item>
      <Form.Item label="索引" name="dataIndex" rules={requiredRule}>
        <Input placeholder="请输入索引" />
      </Form.Item>
      <Form.Item label="类型" name="type" rules={requiredRule}>
        <Select options={typeOptions} />
      </Form.Item>
      <Form.Item label="固定" name="fix" valuePropName="checked">
        <Radio.Group buttonStyle="solid" defaultValue="none">
          <Radio.Button value="none" type="primary">
            无
          </Radio.Button>
          <Radio.Button value="left">左边</Radio.Button>
          <Radio.Button value="right">右边</Radio.Button>
        </Radio.Group>
      </Form.Item>
      <Form.Item
        label="作为搜索项"
        name="search"
        extra="可使用此字段进行数据过滤"
      >
        <Switch />
      </Form.Item>
      <Form.Item wrapperCol={{ offset: 4 }}>
        <Space>
          <Button htmlType="submit" type="primary">
            保存
          </Button>
          <Button htmlType="reset">重置</Button>
          {isDisable && (
            <Link to={undefined} onClick={() => setIsDisable(false)}>
              编辑
            </Link>
          )}
        </Space>
      </Form.Item>
    </Form>
  );
}
